package com.cloud.finance.aviator;

import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.Expression;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class AviatorTest {

    public BigDecimal compileAndExecute(String mathFormula, Map<String, Object> env) {
        // 打印计算公式
        log.info("计算公式:{}", mathFormula);
        Expression compiledExp = AviatorEvaluator.compile(mathFormula);
        // 打印变量和值
        env.entrySet().forEach(e -> {
            log.info("变量:{},值:{}", e.getKey(), e.getValue());
        });
        // 打印结果
        BigDecimal result = (BigDecimal) compiledExp.execute(env);
        log.info("计算结果:{}", result);
        return result;
    }

    public Map<String, Object> getEnv(Object o) {
        Map<String, Object> env = new HashMap<String, Object>();
        Field[] fields = o.getClass().getDeclaredFields();
        for (Field f : fields) {
            Math annotation = f.getAnnotation(Math.class);
            if (null != annotation) {
                String name = annotation.name();
                f.setAccessible(true);
                Object fieldVal = null;
                try {
                    fieldVal = f.get(o);
                } catch (IllegalAccessException e) {
                    log.info("exception:{}", e);
                    throw new RuntimeException(e);
                }
                env.put(name, fieldVal);
            }
        }
        return env;
    }


    public void test(String s,Object o){
        compileAndExecute(s,getEnv(o));
    }
}
